﻿//-----------------------------------------------------------------------
// <copyright file="ObservableObject.cs" company="Bluefragments">
//     Copyright (c) Bluefragments. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;

namespace Quebec.Silverlight.Base
{
    /// <summary>
    /// Provides an implementation of the INotifyPropertyChanged interface.
    /// </summary>
    /// <remarks></remarks>
	public abstract class ObservableObject : INotifyPropertyChanged
	{
        /// <summary>
        /// Occurs when a property value changes.
        /// </summary>
        /// <remarks></remarks>
		public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Called when [property changed].
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        /// <remarks></remarks>
		protected virtual void OnPropertyChanged(string propertyName)
		{
			if (propertyName == null)
				throw new ArgumentNullException("propertyName");

			VerifyProperty(propertyName);

			PropertyChangedEventHandler propertyChangedHandler = PropertyChanged;

			if (propertyChangedHandler != null)
				propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));
		}

        /// <summary>
        /// Verifies the property.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        /// <remarks></remarks>
		[Conditional("DEBUG")]
		private void VerifyProperty(string propertyName)
		{
			PropertyInfo property = GetType().GetProperty(propertyName);

			if (property == null)
			{
				string message = string.Format("Invalid property: {0}", propertyName);
				throw new Exception(message);
			}
		}
	}
}